package com.rock.code.base.dao.impl;

import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.ResultMapping;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * The type Base dao.
 *
 * @author kongqiang
 * @date 2016.12.21
 */
@Repository
public class BaseDaoImpl {

    /**
     * The Sql session.
     */
    @Resource
    private SqlSessionTemplate sqlSession;

    /**
     * Gets db column by property.
     *
     * @param property    the property
     * @param resultMapId the result map id
     * @return the db column by property
     * @author kongqiang
     * @date 2017.03.23
     */
    public String getDbColumnByProperty(String property, String resultMapId) throws Exception {
        ResultMap resultMap = sqlSession.getConfiguration().getResultMap(resultMapId);
        List<ResultMapping> mapping = resultMap.getResultMappings();
        String dbColumn = "";
        for (ResultMapping map : mapping) {
            if (property.equals(map.getProperty())) {
                dbColumn = map.getColumn();
                break;
            }
        }
        return dbColumn;
    }

    public Object queryObject(String statement, Map<String, Object> para) throws Exception {
        return sqlSession.selectOne(statement, para);
    }

    public List<Object> queryObjectList(String statement, Map<String, Object> para) throws Exception {
        return sqlSession.selectList(statement, para);
    }

}
